<script setup>
import { ref } from "vue"

const title = ref("")
const date = ref("")
const arr = ref([])


arr.value = JSON.parse(localStorage.getItem("arr")) || []

const ting = () => {
    title.value = ""
    date.value = ""
}
const add = () => {
    if (title.value === "" || date.value === "") {
        alert("请输入内容")
        return
    }
    console.log("add")

    arr.value.push({
        title: title.value,
        date: date.value,
        id: Date.now(),
    })
    title.value = ""
    date.value = ""
    localStorage.setItem("arr", JSON.stringify(arr.value))
}
const del = (id) => {
    arr.value = arr.value.filter((item) => item.id !== id)
    localStorage.setItem("arr", JSON.stringify(arr.value))
}
const pid = ref("")
const edit = (id) => {
    pid.value = id
    arr.value.forEach((item) => {
        if (item.id === id) {
            title.value = item.title
            date.value = item.date
        }
    })
}
const handleDragStart = (event, key) => {
    event.dataTransfer.setData("text/plain", key)
}
const handleDragOver = (event) => {
    event.preventDefault()
}
const handleDrop = (event, key) => {
    event.preventDefault()
    const key1 = event.dataTransfer.getData("text/plain")
    const temp = arr.value[key]
    arr.value[key] = arr.value[key1]
    arr.value[key1] = temp
}
</script>

<template>
    <!-- 写一个input框 -->
    <span>标题：</span> <input type="text" v-model="title" />
    <span>日期：</span> <input type="date" v-model="date" />
    <br />
    <br />
    <button @click="add">提交</button>
    <br />
    <br />
    <button @click="ting">添加</button>
    <br />
    <br />

    <table>
        <tr>
            <th>标题</th>
            <th>日期</th>
            <th>操作</th>
        </tr>
        <div class="block" draggable="true" v-for="(item, key) in arr" :key="key" @dragstart="handleDragStart($event, key)"
            @dragover="handleDragOver" @drop="handleDrop($event, key)">
            <tr>
                <td>{{ item.title }}</td>
                <td>{{ item.date }}</td>
                <td>
                    <button @click="edit(item.id)">编辑</button>
                    <button @click="del(item.id)">删除</button>
                </td>
            </tr>
        </div>
    </table>
</template>